<script lang="ts" setup>
import * as ItemApi from '@/api/course/item'
import { Form } from '@/components/Form'
import { FormSchema } from '@/types/form'
import { useForm } from '@/hooks/web/useForm'
import SelectContentForm from './select-content-form.vue'

const message = useMessage()
const { t } = useI18n()

const dialogVisible = ref(false)
const dialogTitle = ref('新增课程')
const formLoading = ref(false)
const formType = ref<'create' | 'update'>('create')

const courseId = ref('')
const catalogId = ref('')

const open = (type: 'create' | 'update', _courseId: string, _catalogId: string, id?: string) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'update' ? '编辑条目' : '新增条目'
  formType.value = type
  courseId.value = _courseId
  catalogId.value = _catalogId

  if (type === 'update') {
    formLoading.value = true
    ItemApi.get(id!).then((data) => {
      formMethods.setValues(data)
      formLoading.value = false
    })
  }
}
defineExpose({ open })

const { register: formRegister, elFormRef, methods: formMethods } = useForm()
const schema = reactive<FormSchema[]>([
  {
    field: 'itemName',
    label: '标题',
    component: 'Input',
    value: '',
    formItemProps: { rules: [{ required: true, message: '请输入标题' }] }
  },
  {
    field: 'itemDesc',
    label: '描述',
    component: 'Input',
    componentProps: { type: 'textarea' },
    value: '',
    formItemProps: {
      rules: [
        // 长度不大于100个字符
        {
          max: 100,
          message: '目录描述不可超过100个字',
          trigger: ['blur', 'change']
        }
      ]
    }
  },
  {
    field: 'courseItemType',
    label: '内容类型',
    component: 'RadioButton',
    componentProps: {
      options: ItemApi.CourseItemTypeOptions,
      onChange: () => {
        formMethods.setValues({ courseItemTypeId: '' })
      }
    },
    value: ItemApi.CourseItemType.VIDEO
  },
  {
    field: 'courseItemTypeId',
    label: '内容',
    component: 'Input',
    componentProps: {
      placeholder: '请选择内容',
      onClick: async () => {
        const { courseItemType: type } = (await formMethods.getFormData())!
        openSelectContentForm(type)
      }
    },
    value: '',
    formItemProps: { rules: [{ required: true, message: '请选择内容' }] }
  },
  {
    field: 'isFree',
    label: '免费试看',
    component: 'Switch',
    value: false
  },
  {
    field: 'itemStatus',
    label: '状态',
    component: 'Radio',
    value: ItemApi.CourseItemStatus.ENABLE,
    componentProps: {
      options: ItemApi.CourseItemStatusOptions
    }
  },
  {
    field: 'sortNo',
    label: '排序',
    component: 'InputNumber',
    value: 1
  }
])

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const handleSubmit = async () => {
  // 校验表单
  if (!elFormRef.value) return
  const valid = await elFormRef.value.validate()
  if (!valid) return

  try {
    const formData = (await formMethods.getFormData()) || {}

    if (formType.value === 'create') {
      // 新增
      const data: ItemApi.CourseItemCreateDTO = {
        ...(formData as any),
        courseId: courseId.value,
        catalogId: catalogId.value
      }

      await ItemApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      // 更新
      const data: ItemApi.CourseItemUpdateDTO = {
        ...(formData as any),
        courseId: courseId.value,
        catalogId: catalogId.value
      }

      await ItemApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const selectContentFormRef = ref()
const openSelectContentForm = (type: ItemApi.CourseItemType) => {
  selectContentFormRef.value.open(type)
}
const handleContentSelect = (id: string) => {
  formMethods.setValues({ courseItemTypeId: id })
  selectContentFormRef.value.close()
}
</script>

<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="600">
    <Form @register="formRegister" :schema="schema" />

    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="handleSubmit">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <SelectContentForm ref="selectContentFormRef" width="80%" @select="handleContentSelect" />
</template>
